package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ChenPi
 * @since 2024/12/05 10:26
 */
@RestController
@RequestMapping("/users")
@Api(tags = "用户管理")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    @ApiOperation("新增用户接口")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userDTO) {
        User user = BeanUtil.copyProperties(userDTO, User.class);
        userService.save(user);
    }

    @ApiOperation("删除用户接口")
    // DELETE/users/{id}
    @DeleteMapping("/{id}")
    public void deleteUserById(@ApiParam("用户ID") @PathVariable("id") Long id) {
        userService.removeById(id);
    }

    @ApiOperation("查询用户接口")
    @GetMapping("/{id}")
    public UserVO selectUserById(@ApiParam("用户ID") @PathVariable("id") Long id) {
        // User user = userService.getById(id);
        // return BeanUtil.copyProperties(user, UserVO.class);

        return userService.queryUserAndAddressById(id);
    }

    @ApiOperation("查询用户列表接口")
    @GetMapping
    public List<UserVO> selectUserByIds(@ApiParam("用户ID集合") @RequestParam("ids") List<Long> ids) {
        // List<User> users = userService.listByIds(ids);

        // // 1.使用hutool工具类
        // BeanUtil.copyToList(users, UserVO.class);
        // // 2.使用stream流
        // users.stream()
        //         .map(user -> BeanUtil.copyProperties(user, UserVO.class))
        //         .collect(Collectors.toList());

        // return BeanUtil.copyToList(users, UserVO.class);

        return userService.queryUsersWithAddress(ids);
    }

    @ApiOperation("扣减用户余额接口")
    @PutMapping("/{id}/deduction/{money}")
    public void deductionBalanceById(@ApiParam("用户ID") @PathVariable("id") Long id, @ApiParam("扣减金额") @PathVariable("money") Integer money) {
        userService.deductionBalanceById(id, money);
    }

    @ApiOperation("根据复杂条件查询用户列表接口")
    @GetMapping("/list")
    public List<UserVO> selectUsers(UserQuery query) {

        List<User> users = userService.queryUsers(query);

        return BeanUtil.copyToList(users, UserVO.class);
    }

    @ApiOperation("根据分页条件查询用户列表接口")
    @GetMapping("/page")
    public PageDTO<UserVO> queryUsersPage(UserQuery query) {
        return userService.queryUsersPage(query);
    }



}
